
#include <jsoncpp/json/json.h>//用find命令查找json的头文件和库文件
#include <string>

using namespace std;

namespace Protocol
{
    const string Sep="\r\n";

    void EnLenHeader(string& message)//添加长度报头
    {
        int len =message.size();
        string s= to_string(len);
        s+= Sep;
        s+= message;
        s.swap(message);
    }

    bool DeLenHeader(string& package, string* out)
    {
        int pos= package.find(Sep);
        if(pos== string::npos)
        {
            return false;
        }

        int len= stoi(package.substr(0, pos));
        if(package.size()< pos+Sep.size()+len)
        {
            return false;
        }

        *out= package.substr(pos+ Sep.size(), len);

        package.erase(0, pos+Sep.size()+ len);
        return true;
    }

    class Request
    {
    public:
        Request()
        :_x(0)
        ,_y(0)
        ,_op(0)
        {}

        Request(int x,int y,char op)
        :_x(x)
        ,_y(y)
        ,_op(op)
        {}

        string Serialize()
        {
            Json::Value root;
            root["data1"]= _x;
            root["data2"]= _y;
            root["oper"]= _op;

            return root.toStyledString();
        }

        void DeSerialize(string& message)
        {
            Json::Value t;
            Json::Reader reader;
            reader.parse(message, t);

            _x= t["data1"].asInt();
            _y= t["data2"].asInt();
            _op= t["oper"].asInt();

        }

        int _x;
        int _y;
        char _op;    
    };


    class Response
    {
    public:
        Response()
        :_result(0)
        ,_code(0)
        {}

        Response(int result, int code)
        :_result(result)
        ,_code(code)
        {}

        string Serialize()
        {
            Json::Value root;
            root["result"]= _result;
            root["code"]= _code;
            return root.toStyledString();
        }

        void DeSerialize(string& message)
        {
            Json::Value t;
            Json::Reader reader;
            reader.parse(message, t);

            _result= t["result"].asInt();
            _code= t["code"].asInt();
        }

        int _result;//响应结果
        int _code;//响应码
    };




}